import React, { useState, useEffect } from 'react';
import { Table, Button, Pagination, Modal, Form, Input, Upload, } from 'antd';
import Pannel from '../../../component/pannel';
import { delgoods, getGoodsList, editgoods, getgoodsInfo, uploadGoodsImg } from '../../../api/account';
import './goolist.less';
const GoodsList = () => {
    const [editModalVisible, setEditModalVisible] = useState(false);
    const [editingGoods, setEditingGoods] = useState(null);
    const [data, setData] = useState([]);
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(5);
    const columns = [
        {
            title: '商品名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '所属分类',
            dataIndex: 'category',
            key: 'category',
        },
        {
            title: '商品价格',
            dataIndex: 'price',
            key: 'price',
        },
        {
            title: '商品图片',
            dataIndex: 'imgUrl',
            key: 'imgUrl',
            render: (imgUrl) => <img src={`http://8.137.157.16:9002${imgUrl}`} alt="" />,
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <>
                    <Button onClick={() => showEditModal(record)}>编辑</Button>
                    <Button type="primary" danger onClick={() => handleDelGoods({ id: record.id })}>删除</Button>
                </>
            ),
        },
    ];
    //列表展示代码
    useEffect(() => {
        fetchData();
    }, [currentPage, pageSize]);
    const fetchData = async () => {
        try {
            const res = await getGoodsList({ currentPage, pageSize });
            if (Array.isArray(res.data.data)) {
                setData(res.data.data);
            }
        } catch (error) {
            console.error('', error);
        }
    };
    //删除商品逻辑代码
    const handleDelGoods = async (id) => {
        try {
            const res = await delgoods(id);
            console.log(res.data);
            if (res.data.code == 0) {
                const newData = data.filter(item => item.id !== id);
                setData(newData);
                fetchData();
            }
        } catch (error) {
            console.error('', error);
        }
    };
    //修改商品信息代码--有bug
    const showEditModal = (goods) => {
        setEditingGoods(goods);
        setEditModalVisible(true);
    };

    const handleEditSubmit = async (editedGoods) => {
        try {
            const res = await editgoods(editedGoods);
            console.log(res.data);
            if (res.data.code == 0) {
                const updatedData = data.map(item => item.id === editedGoods.id ? editedGoods : item);
                setData(updatedData);
                setEditModalVisible(false);
                fetchData();
            }
        } catch (error) {
            console.error(error);
        }
    };
    const EditGoodsForm = ({ goods, onSubmit }) => {
        const [name, setName] = useState(goods ? goods.name : '');
        const [category, setcategory] = useState(goods ? goods.category : '');
        const [price, setprice] = useState(goods ? goods.price : '');
        const [imgUrl, setimgUrl] = useState(null);
        const [goodsDesc, setgoodsDesc] = useState(goods ? goods.goodsDesc : '');
        const [id, setid] = useState(goods ? goods.id : '');
        const handleSubmit = (e) => {
            e.preventDefault();
            onSubmit({ id: goods.id, name, category, price, imgUrl, goodsDesc });
        };
        // const [imgUrl, setImgUrl] = useState("");
        const [imgItem, setImgItem] = useState("");
        const handleChange = async ({ file }) => {
            const formData = new FormData();
            formData.append('file', file);
            const res = await uploadGoodsImg(formData);
            console.log(res.data.imgUrl);
            if (res.data.code == 0) {
                // setimgUrl(`http://8.137.157.16:9002${res.data.imgUrl}`);
                let index = res.data.imgUrl.lastIndexOf('/');
                setImgItem(res.data.imgUrl.substring(index + 1));
                console.log(res.data.imgUrl.substring(index + 1));
                setimgUrl(res.data.imgUrl.substring(index + 1));
            }
        };
        return (
            <Form onSubmit={handleSubmit}>
                <Form.Item label="商品名称">
                    <Input value={name} onChange={(e) => setName(e.target.value)} />
                </Form.Item>
                <Form.Item label="商品分类">
                    <Input value={category} onChange={(e) => setcategory(e.target.value)} />
                </Form.Item>
                <Form.Item label="商品价格">
                    <Input value={price} onChange={(e) => setprice(e.target.value)} />
                </Form.Item>
                <Form.Item label="商品图片">
                    {/* <Input value={imgUrl} onChange={(e) => setimgUrl(e.target.value)} /> */}
                    {/* <img src={"http://8.137.157.16:9002/upload/imgs/goods_img" + imgUrl} alt="" /> */}
                    <Upload
                        accept="image/png, image/jpeg"
                        customRequest={handleChange}
                        listType="picture-card"
                        showUploadList={false}
                    >
                        {"http://8.137.157.16:9002/upload/imgs/goods_img" + imgUrl ? (
                            <img src={`http://8.137.157.16:9002${goods.imgUrl}`} alt="" style={{ width: 105, height: 105 }} />
                        ) : (<button
                            style={{
                                border: 0,
                                background: 'none',
                            }}
                            type="button"
                        >
                        </button>)}

                    </Upload>
                </Form.Item>
                <Form.Item label="商品描述">
                    <Input value={goodsDesc} onChange={(e) => setgoodsDesc(e.target.value)} />
                </Form.Item>
                <Form.Item label="商品ID">
                    <Input value={id} onChange={(e) => setid(e.target.value)} />
                </Form.Item>

                <Button type="primary" htmlType="submit" onClick={handleSubmit}>提交</Button>
            </Form>
        );
    };

    return (
        <Pannel title='商品列表'>
            <div className="goods-list">
                <Table
                    columns={columns}
                    dataSource={data}
                    pagination={false}
                    rowKey="id"
                    expandable={{
                        expandedRowRender: (record) => (
                            <p
                                style={{
                                    margin: 0,
                                }}
                            >
                                <div className='goodsDetail'>
                                    商品ID:<div>{record.id}</div>
                                    商品名称:<div>{record.name}</div>
                                    商品价格:<div>{record.price}</div>
                                    商品分类:<div>{record.category}</div>
                                    商品描述:<div>{record.goodsDesc}</div>
                                    商品图片:<div><img src={"http://8.137.157.16:9002" + record.imgUrl} /></div>


                                </div>
                            </p>
                        ),
                        rowExpandable: (record) => record.name !== 'Not Expandable',
                    }}
                />
            </div>
            <div className="page3">
                <Pagination
                    current={currentPage}
                    total={500}
                    onChange={page => setCurrentPage(page)}
                    onShowSizeChange={(current, size) => setPageSize(size)}
                />
            </div>
            <Modal
                title="编辑商品"
                visible={editModalVisible}
                onCancel={() => setEditModalVisible(false)}
                footer={null}
            >
                <EditGoodsForm goods={editingGoods} onSubmit={handleEditSubmit} />
            </Modal>
        </Pannel>
    );
};


export default GoodsList;